//
//  UserCenterViewController.m
//  HuLaQuan
//
//  Created by hok on 1/14/16.
//  Copyright © 2016 Jianghao. All rights reserved.
//

#import "UserCenterViewController.h"

//Cells
#import "UserCenterNewCell.h"
#import "UserCenterTopCell.h"

//Home Parent Controller
#import "HomeTabBarController.h"


#import "NSString+PhotoDir.h"

//Logic model
#import "GetUserDetailInfoEngine.h"

//Jump To
#import "UserDetailedInfoViewController.h"
#import "UserPaySettingController.h"

@interface UserCenterViewController ()


@property (nonatomic,strong) NSMutableArray *userInfoItems;   // User Center Items

@property (nonatomic,strong) NSMutableDictionary *userPersonalInfo;


//Logic Model
@property (nonatomic,strong) GetUserDetailInfoEngine *getUserInfoEngine; // 获取用户个人信息
@end

static NSString * const UserCenterCellIdentifier = @"UserCenterNewCellIdentifier";
static NSString * const UserCenterTopCellIdentifier = @"UserCenterTopCell";
@implementation UserCenterViewController

/**
 *  逻辑模型，用来获取用户个人信息并显示在Top栏
 *
 *  @return <#return value description#>
 */
- (GetUserDetailInfoEngine *)getUserInfoEngine
{
    if (!_getUserInfoEngine) {
        _getUserInfoEngine = [[GetUserDetailInfoEngine alloc] init];
    }
    return _getUserInfoEngine;
}
-(NSMutableArray *)userInfoItems{
    if (!_userInfoItems) {
        _userInfoItems=[NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"UserCenter" ofType:@"plist"]];
    }
    return _userInfoItems;
}
- (void)setupUI
{
    [self.tableView registerNib:[UserCenterNewCell nib] forCellReuseIdentifier:UserCenterCellIdentifier];
    [self.tableView registerNib:[UserCenterTopCell nib] forCellReuseIdentifier:UserCenterTopCellIdentifier];
    
    [self setupFooterForTableView];
    
    self.tableView.backgroundColor = UIColorFromRGBA(kBackgroundColor, 1.0);
    
    
    self.title = @"我的";

}

#pragma mark - TableView Delegate
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0.000001;
    }else{
        return kUserCenterSectionHeaderHeight;
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.000001;
}
/*- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
 {
 CGFloat tableHeight = [tableView headerViewForSection:section].frame.size.height;
 NSLog(@"%f",tableHeight);
 /* if (section!=0)
 {
 UIView * head=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 2)];
 return head ;
 }
 else
 {
 UIView * head=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 0)];
 return head ;
 
 }
 UIView * head=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 0)];
 return head ;
 }*/
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
            
            return kUserCenterTopCellHeight;
            
            
            break;
        case 1:
        {
            
            
            return kUserCenterCellHeight;
            
            
            
        }
            break;
        case 2:
            return kUserCenterCellHeight;
            break;
        default:
            return 0;
            break;
    }
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return self.userInfoItems.count - 2;
            break;
            
        default:
            return 0;
            break;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            
            UserCenterTopCell *cell = [tableView dequeueReusableCellWithIdentifier:UserCenterTopCellIdentifier
                                                                      forIndexPath:indexPath];
            
            /*cell.userName.text = [CurrentUser sharedInstance].name;
             
             NSString *age = [CurrentUser sharedInstance].userInfo.userInformations[@"age"];
             NSString *realname = [CurrentUser sharedInstance].userInfo.userInformations[@"realname"];
             NSString *degree = [CurrentUser sharedInstance].userInfo.userInformations[@"gender"];
             
             if (age.length ==0  && degree.length ==0  && realname.length ==0 ) {
             cell.userInfo.text = @"请完善个人信息";
             }else{
             cell.userInfo.text = [NSString stringWithFormat:@"%@%@%@",[realname isEqual:[NSNull null]] ? @"" : [realname stringByAppendingString:@"    "],[degree isEqual:[NSNull null]] ? @"" : [degree stringByAppendingString:@"   "],[age isEqual:[NSNull null]] ? @"" : age];
             }*/
            if (self.userPersonalInfo) {
                cell.userName.text = ([self.userPersonalInfo[@"realName"] isEqualToString:@"Anonymous"]) ?  @"呼啦圈用户" : self.userPersonalInfo[@"realName"];
                
                if (self.userPersonalInfo[@"avatar"] ) {
                    NSFileManager *fileManager = [NSFileManager defaultManager];
                    
                    NSString *filePath = [NSString stringWithFormat:@"%@/%@",[NSString photoDir],kTempLocalAvatarName];
                    
                    
                    if(![fileManager fileExistsAtPath:filePath])
                    {
                        cell.userImage.image = [UIImage imageNamed:@"default_user"];
                    }else{
                        cell.userImage.image = [UIImage imageWithContentsOfFile:filePath];
                    }
                    
                }else{
                    cell.userImage.image = [UIImage imageNamed:@"default_user"];
                }
                
            }
            
            return cell;
            
            
            
        }
            break;
        case 1:
        {
            
            
            UserCenterNewCell *cell = [tableView dequeueReusableCellWithIdentifier:UserCenterCellIdentifier
                                                                      forIndexPath:indexPath];
            
            /* int index = -1;
             if (indexPath.row < 3) {
             index = indexPath.row;
             }else if (indexPath.row > 3 && indexPath.row < 7){
             index = indexPath.row - 1;
             }else if (indexPath.row > 7 && indexPath.row < 10){
             index = indexPath.row - 2;
             }else{
             
             }*/
            
            cell.title.text = self.userInfoItems[indexPath.row][@"title"];
            //                    cell.icon.image = [UIImage imageNamed:self.userInfoItems[indexPath.row][@"imageName"]];
            
            
            
            // cell.indexPath = indexPath;
            /*if (indexPath.row == [self.userInfoItems count] -1) {
             cell.datailedLabel.text = [VersionUpdateEngine currentVersion];
             cell.arrow.hidden = YES;
             }*/
            return cell;
            
            
            
        }
            break;
            //        case 2:
            //        {
            //            UserCenterNewCell *cell = [tableView dequeueReusableCellWithIdentifier:UserCenterCellIdentifier
            //                                                                   forIndexPath:indexPath];
            //
            //
            //            NSInteger index = indexPath.row + 1;
            //                cell.title.text = self.userInfoItems[index][@"title"];
            ////                cell.icon.image = [UIImage imageNamed:self.userInfoItems[index][@"imageName"]];
            //
            //
            //
            //            // cell.indexPath = indexPath;
            //            /*if (indexPath.row == [self.userInfoItems count] -1) {
            //             cell.datailedLabel.text = [VersionUpdateEngine currentVersion];
            //             cell.arrow.hidden = YES;
            //             }*/
            //            return cell;
            //
            //
            //
            //        }
            //            break;
            
        default:
        {
            
            return nil;
            
            
        }
            break;
    }
//    return nil;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    switch (indexPath.section) {
        case 0:
            [self performSegueWithIdentifier:@"ShowUserDetailedInfoViewController" sender:self];
        break;
        case 1:
        {
            switch (indexPath.row) {
                
                case 0:
                    [self performSegueWithIdentifier:@"ShowUserFeedBackViewController" sender:self];
                    break;
                case 1:
                    [self performSegueWithIdentifier:@"ShowUserAboutUsViewController" sender:self];
                    break;
                case 2:
                    [self performSegueWithIdentifier:@"ShowUserSettingsViewController" sender:self];
                    break;
                case 3:
                    [self performSegueWithIdentifier:@"ShowBankCardFromMy" sender:self];
                    
                    break;
                case 4:
                    [self performSegueWithIdentifier:@"ShowUserSecurityViewController" sender:self];
                    break;
                case 5:
                    [self performSegueWithIdentifier:@"ShowUserPaySettingController" sender:self];
                    break;
                case 6:
                    [self performSegueWithIdentifier:@"ShowUserInviteingFriends" sender:self];
                    break;
                default:
                    break;
            }
       }
            break;
            
            
        default:
            break;
    }
    
}

#pragma mark - Call Back
- (void)getUserInfoFinish:(NSNotification*) notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        self.userPersonalInfo = [messageDic[@"result"] mutableCopy];
        [self.tableView reloadData];
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
}

#pragma mark - Life Cycle
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [(HomeTabBarController *)self.tabBarController setTabBarHidden:NO];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUserInfoFinish:) name:@"GetUserInfoFinish" object:nil];
    
    [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
    [self.getUserInfoEngine getUserInfo];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetUserInfoFinish" object:nil];
    
}
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    
    [(HomeTabBarController *)self.tabBarController setTabBarHidden:YES];
    
  
    if([segue.identifier isEqualToString:@"ShowUserDetailedInfoViewController"]){
        UserDetailedInfoViewController *controller = (UserDetailedInfoViewController *)[segue destinationViewController];
        controller.userInfo = [self.userPersonalInfo  copy];
        controller.getUserInfoEngine = self.getUserInfoEngine;
    }
    
    
    if([segue.identifier isEqualToString:@"ShowUserPaySettingController"]){
        UserPaySettingController *controller = (UserPaySettingController *)[segue destinationViewController];
        controller.userInfo = [self.userPersonalInfo  copy];
        controller.isFromUserCenter = YES;
    }
}

@end
